package android.longs.study.home.servlet.dao;

import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.criterion.Restrictions;

import android.longs.study.home.servlet.model.MobleHomeModel;
import android.longs.study.utils.H3Utils;
import android.longs.study.utils.HBUtils;

public class MobleHomeDaoImple implements MobleHomeDao {

    @Override
    public List<MobleHomeModel> queryAll(int start) {
	Session currentSession = H3Utils.getCurrentSession();
	
	//QBC方式查询
	Criteria createCriteria = currentSession.createCriteria(MobleHomeModel.class);
	createCriteria.setFirstResult(start);
	createCriteria.setMaxResults(15);
	
	List<MobleHomeModel> list = createCriteria.list();
	
	return list;
    }
    @Override
    public List<MobleHomeModel> queryAll() {
	Session currentSession = H3Utils.getCurrentSession();
	currentSession.beginTransaction();
	//QBC方式查询
	Criteria createCriteria = currentSession.createCriteria(MobleHomeModel.class);
	
	List<MobleHomeModel> list = createCriteria.list();
	currentSession.getTransaction().commit();
	return list;
    }

    @Override
    public void add(MobleHomeModel model) {
	if (model==null) {
	    return;
	}
	Session session = HBUtils.openSession();
	//4 开启事务
	Transaction transaction = session.beginTransaction();
	//**** 操作
	session.save(model);

	//5 提交
	transaction.commit();
	//6 释放
	session.close();

    }



    @Override
    public void updateModel(MobleHomeModel model) {
	// TODO Auto-generated method stub

	Session session = HBUtils.openSession();
	Transaction beginTransaction = session.beginTransaction();
	session.saveOrUpdate(model);
	beginTransaction.commit();
	session.close();

    }

    @Override
    public MobleHomeModel queryFromUidHomeModel(String uid) {
	Session session = HBUtils.openSession();
	Transaction beginTransaction = session.beginTransaction();
	//通过uid来查询
	MobleHomeModel userModel = (MobleHomeModel) session.createCriteria(MobleHomeModel.class)
		.add(Restrictions.eq("uid",uid))	
		.uniqueResult();


	beginTransaction.commit();
	session.close();
	return userModel;
    }

    @Override
    public MobleHomeModel queryFromNameHomeModel(String name) {
	Session session = HBUtils.openSession();
	Transaction beginTransaction = session.beginTransaction();
	//通过uid来查询
	MobleHomeModel userModel = (MobleHomeModel) session.createCriteria(MobleHomeModel.class)
		.add(Restrictions.eq("name",name))	
		.uniqueResult();


	beginTransaction.commit();
	session.close();
	return userModel;
    }

    @Override
    public void deleteModelFromName(String name) {
	String hql;
	Session session = HBUtils.openSession();


	//4 开启事务
	Transaction transaction = session.beginTransaction();

	hql = "delete MobleHomeModel where name = :oldName";
	int deleteEntities = session.createQuery(hql)
		.setString("oldName",name)
		.executeUpdate();

	transaction.commit();
    }


}
